package com.briup.sms.service.impl;

import com.briup.sms.dao.AdminMapper;
import com.briup.sms.entity.Admin;
import com.briup.sms.service.AdminService;
import com.briup.sms.utils.JWTUtils;
import com.briup.sms.utils.ResultCode;
import com.briup.sms.utils.SMSException;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author :xuyang
 * @DateTime:2024/1/10 11:16
 * @Version :v1.0.0
 * ClassName:AdminServiceImpl
 * Package  :com.briup.sms.service.impl
 * Description:TODO
 */
@Service
public class AdminServiceImpl implements AdminService {
    @Autowired
    private AdminMapper mapper;

    @Override
    public Map login(Admin admin) {
        HashMap<String, String> map = new HashMap<>();
        Admin user = mapper.selectByUserName(admin.getUsername());
        if (user == null)
            throw new SMSException(ResultCode.USER_NOT_EXIST);
        if (!user.getStats())
            throw new SMSException(ResultCode.USER_ACCOUNT_FORBIDDEN);
        if (user.getPassword().equals(admin.getPassword())) {
            map.put("username", user.getUsername());
            map.put("avatar", user.getAvatar());
            map.put("token", JWTUtils.generatorToken("username", user.getUsername()));
            return map;
        } else {
            throw new SMSException(ResultCode.USER_LOGIN_ERROR);
        }
    }

    @Override
    public Admin getInfo(String token) {
        Map<String, Object> map = JWTUtils.paresToken(token);
        String username = (String) map.get("username");
        Admin admin = mapper.selectByUserName(username);
        return admin;
    }

    @Override
    public PageInfo<Admin> getPageUser(String username, Boolean stats, Integer pageSize, Integer pageNum) {
        List<Admin> List = mapper.getPageUser(username, stats);
        PageInfo<Admin> pageInfo = new PageInfo<>(List);
        return pageInfo;
    }

    @Override
    public void saveUser(Admin admin) {
        if (admin.getId() == null) {
            mapper.addUser(admin);
        } else {
            mapper.updateUser(admin);
        }
    }


}
